<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24" style="padding: 5%">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="ruleFormRef"
        >
          <h1>Hello</h1>
          <h2>欢迎来到新南科技</h2>
          <div style="padding: 0 30px">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder=""
                size="default"
                clearable
                @change=""
                :prefix-icon="User"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                placeholder=""
                size="default"
                clearable
                @change=""
                type="password"
                :prefix-icon="Lock"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                class="login_btn"
                :loading="loading"
                :disabled="loading"
                type="primary"
                size="default"
                @click="clickLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import useUserStore from '../../store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '../../utils/time'
let userStore = useUserStore()
let router = useRouter()
let route = useRoute()

//获取表单实例
//在 Vue 组件里，ref 属性是一个很实用的特性，主要用于获取组件实例或者 DOM 元素的引用
let ruleFormRef = ref()

//控制按钮加载效果
let loading = ref(false)

//收集账号与密码数据
const loginForm = reactive({
  username: 'admin',
  password: '111',
})
//登录按钮回调
const clickLogin = async () => {
  //保证表单校验通过后再发请求
  await ruleFormRef.value.validate()

  //加载效果
  loading.value = true
  // console.log('登录');
  //通知仓库发登录请求
  //请求成功=>首页展示数据的地方
  //请求失败=>弹出登录失败信息
  try {
    //可以书写.then的语法
    //保证登录成功
    await userStore.userLogin(loginForm)
    //编程式导航跳转到展示数据首页
    //判断登录的时候，路由路径是否携带query参数，有则跳转到query参数指定的路径，没有则跳转到首页
    if (route.query?.redirect) {
      router.push(route.query.redirect as string)
    } else {
      router.push('/')
    }
    //登录成功提示
    ElNotification({
      title: `HI,${getTime()}好!`,
      message: '欢迎来到新南科技',
      type: 'success',
      offset: 60,
    })
    //登录成功，加载效果消失
    loading.value = false
  } catch (error) {
    //登录失败，加载效果消失
    loading.value = false
    //登录失败的提示信息0
    ElNotification({
      title: '登录失败',
      message: (error as Error).message,
      type: 'error',
    })
  }
}
//自定义校验规则函数
//rule:校验规则对象
//value:校验的值
//callback:回调函数，校验通过不传参，校验不通过注入错误信息
const validatorUserName = (rule: any, value: any, callback: any) => {
  if (value.length < 5 || value.length > 10) {
    callback(new Error('用户名长度在5到10个字符'))
  } else {
    callback()
  }
}
//定义表单校验规则
const rules = {
  //required:是否必填项，message:错误提示信息，trigger:触发时机（blur失去焦点，change内容改变）
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    // { min: 5, max: 10, message: '用户名长度在5到10个字符', trigger: 'change' }
    //自定义校验规则
    { validator: validatorUserName, trigger: 'change' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 15, message: '密码长度在3到15个字符', trigger: 'change' },
  ],
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/img/bg1.png') no-repeat;
  background-size: 100% 100%;

  .login_form {
    position: relative;
    width: 75%;
    top: 25vh;
    background-color: rgba(255, 255, 255, 0.5);
    padding: 4%;

    h1 {
      color: #0e5292;
    }

    h2 {
      margin-bottom: 10px;
      color: #0e5292;
    }

    .login_btn {
      width: 100%;
      /* margin-top: 10px; */
    }
  }
}
</style>
